import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_out_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_out.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/delivery.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/ship_the_products.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_packing.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_product_register.dart';
import 'package:flutter_admin/pages/odoo/material/hw_check/hw_weigh.dart';
import 'package:flutter_admin/pages/odoo/material/location_out/location_out_confirmation.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

import 'hw_check_dialog.dart';
import 'hw_warehousing.dart';

class HWCheckDetail extends StatefulWidget {
  HWCheckDetail({Key? key,required this.huaweiCheckId}) : super(key: key);

  String huaweiCheckId;

  @override
  _HWCheckDetailState createState() => _HWCheckDetailState();
}

class _HWCheckDetailState extends State<HWCheckDetail> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'is_packaging', asc: false)]);
  List<StockQuant> selectedList = [];
  StockQuant stockQuant = StockQuant();
  var _subscription;

  @override
  void initState() {
    super.initState();
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "HWCheckDetail")
        .listen(_onEnvent);
    stockQuant.huaweiCheckId = widget.huaweiCheckId;
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) async{
    try {
      var scan = obj["scan"].toString();
      var res = await DynamicDataApi.getModels(model: 'stock.quant',key: 'internal_print_str',val: scan);
      if (!res.success! || res.data.length == 0) {
        CryUtils.message("$scan未进行包装！");
        return;
      }
      if(res.data[0]['is_weigh'] == '1'){
        CryUtils.message("$scan已经称重完成！");
        return ;
      }
      StockQuant stockQuant = StockQuant.fromHWMap(res.data[0]);
      _HWWtigh(stockQuant);
    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('销售单号')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('操作人')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('是否包装')),
        DataColumn(label: Text('是否称重')),
      ],
      getCells: (m) {
        StockQuant stockQuant = StockQuant.fromHWMap(m);
        return [
          DataCell(Text(stockQuant.saleorder ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.productUomName ?? '--')),
          DataCell(Text(stockQuant.username ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productorderno ?? '--')),
          DataCell(Text(stockQuant.isPackaging == '1'?'是':'否')),
          DataCell(Text(stockQuant.isWeigh == '1'?'是':'否')),
        ];
      },
    );
    _getSelectList();
    var result = Scaffold(
      appBar: AppBar(
        title: Text('明细数据'),
      ),
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _HWPackiong(id) async{
    StoreUtil.write("key", "HWPacking");
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: HWPacking(id: id,),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _HWWtigh(StockQuant stockQuant) async{
    StoreUtil.write("key", "HWWtigh");
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: HWWeigh(stockQuant: stockQuant,),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _query() {
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.HWDetailPage(
        data: {"page": page, "domainList": stockQuant.toHWDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<StockQuant>((e) => StockQuant.fromHWMap(e))
        .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          // _search();
        } else if (v == OperationType.reset) {
          // _HWProductRegister();
        } else if (v == OperationType.add) {
          // _HWPrint('internal_print', selectedList[0].id);
        } else if (v == OperationType.edit) {
          // _HWPrint('exterior_print', selectedList[0].id);
        } else if (v == OperationType.delete) {
          _HWPackiong(selectedList[0].id);
        } else if (v == OperationType.lendOrReturn) {
          // _HWWtigh(selectedList[0]);
        } else if (v == OperationType.dmsFile) {
          // _HWWarehousing(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        // PopupMenuItem<OperationType>(
        //   value: OperationType.query,
        //   child: ListTile(
        //     leading: const Icon(Icons.search),
        //     title: Text('查询'),
        //   ),
        // ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length == 1 && selectedList[0].isPackaging != '1',
          child: ListTile(
            leading: const Icon(Icons.view_headline),
            enabled: selectedList.length == 1  && selectedList[0].isPackaging != '1',
            title: Text('包装'),
          ),
        ),
        // PopupMenuItem<OperationType>(
        //   value: OperationType.lendOrReturn,
        //   enabled: selectedList.length == 1 && selectedList[0].isWeigh != '1',
        //   child: ListTile(
        //     leading: const Icon(Icons.view_headline),
        //     enabled: selectedList.length == 1 && selectedList[0].isWeigh != '1',
        //     title: Text('称重'),
        //   ),
        // ),
      ],
    );
  }
}
